<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="30vw" :title="`${drawerProps.title}问题`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="问题图片" prop="fileList">
        <UploadImgs v-model:file-list="drawerProps.row!.fileList" height="140px" width="140px" :prefix-data="QA">
          <template #empty>
            <el-icon><Picture /></el-icon>
            <span>请上传照片</span>
          </template>
          <template #tip> 照片大小不能超过 5M </template>
        </UploadImgs>
      </el-form-item>
      <el-form-item label="分类" prop="typeId">
        <el-cascader
          v-model="drawerProps.row!.typeId"
          :options="options"
          placeholder="请选择分类"
          clearable
          :props="defaultOptions"
          ref="cascaderRef"
        />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="drawerProps.row!.title" placeholder="请填写标题" clearable></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input
          class="at-h"
          rows="10"
          type="textarea"
          v-model="drawerProps.row!.content"
          placeholder="请填写内容"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item v-show="drawerProps.title == '查看'" label="浏览次数" prop="viewNumber">
        <el-input v-model="drawerProps.row!.viewNumber" placeholder="请填写浏览次数" clearable></el-input>
      </el-form-item>
      <el-form-item label="悬赏" prop="reward">
        <el-input v-model="drawerProps.row!.reward" placeholder="请填写悬赏" clearable></el-input>
      </el-form-item>
      <!-- <el-form-item label="备注" prop="remark">
        <el-input v-model="drawerProps.row!.mobile" placeholder="请填写备注" clearable></el-input>
      </el-form-item> -->
      <!-- <el-form-item v-show="drawerProps.isView" label="修改人" prop="modifiedBy">
        <el-input v-model="drawerProps.row!.modifiedBy" placeholder="请填写备注" clearable></el-input>
      </el-form-item>
      <el-form-item v-show="drawerProps.isView" label="修改时间" prop="gmtModified">
        <el-input v-model="drawerProps.row!.gmtModified" placeholder="" clearable></el-input>
      </el-form-item>
      <el-form-item v-show="drawerProps.isView" label="创建人" prop="createBy">
        <el-input v-model="drawerProps.row!.createBy" placeholder="" clearable></el-input>
      </el-form-item>
      <el-form-item v-show="drawerProps.isView" label="创建时间" prop="gmtCreate">
        <el-input v-model="drawerProps.row!.gmtCreate" placeholder="" clearable></el-input>
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false"> 取消 </el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
// import { genderType } from "@/utils/serviceDict";
import { ElMessage, FormInstance } from "element-plus";
import { User, File, Dict } from "@/api/interface";
import UploadImgs from "@/components/Upload/Imgs.vue";
import { getDict, getParamTreeByChildId } from "@/api/modules/sys";
const cxt = getCurrentInstance();
const dict = cxt?.appContext.config.globalProperties.$dict;
import { QA } from "@/constants";
// 分类查询
let options = ref();
let defaultOptions = ref();
// 加载字典数据
const loadNode = async (node: Node, resolve: (data: Dict.ResDictList[]) => void) => {
  if (node.value) {
    const { data } = await drawerProps?.value.getDict({ parentId: node.value });
    resolve(data);
  }
};
const rules = reactive({
  fileList: [{ required: true, message: "请上传图片" }],
  title: [{ required: true, message: "请填写标题" }],
  content: [{ required: true, message: "请填写内容" }],
  typeId: [{ required: true, message: "请选择分类" }],
  email: [{ required: true, message: "请填写邮箱" }],
  reward: [{ required: false, pattern: /^[0-9]+$/, message: "请填写数字" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<User.ResUserList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  getDict: (params: any) => Promise<any>;
  fileList: File.ResFileList[];
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {
    fileList: []
  }
});

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  // 保存
  defaultOptions.value = {
    lazy: true,
    label: "name",
    value: "id",
    checkStrictly: true,
    lazyLoad: loadNode
  };
  if (params.row.typeId) {
    let result = await getParamTreeByChildId({ childId: params.row.typeId });
    drawerProps.value.row.typeId = result.data.splice(1);
  }
};
// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      const questionImg = drawerProps.value.row.fileList.map(item => {
        return {
          name: item.originalFileName || item.name,
          path: item.path,
          questionId: drawerProps.value.row.id
        };
      });
      drawerProps.value.row.questionImg = questionImg;

      drawerProps.value.row.typeId = Array.isArray(drawerProps.value.row.typeId)
        ? drawerProps.value.row.typeId[drawerProps.value.row.typeId.length - 1]
        : drawerProps.value.row.typeId;
      delete drawerProps.value.row.fileList;
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}问题成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
onMounted(async () => {
  const { data } = await getDict!({ parentId: dict.questionId });
  options.value = data;
});
defineExpose({
  acceptParams
});
</script>
<style scoped="sass">
.el-textarea__inner {
  height: 80px;
}
</style>
